package com.example.administrator.daydayappmarket.search.fragment;


/**
 * TODO 搜索列表fragment
 */

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.Encoder;
import com.example.administrator.daydayappmarket.Contacts;
import com.example.administrator.daydayappmarket.R;
import com.example.administrator.daydayappmarket.recommend.adapter.RecommendMainFootListViewAdapter;
import com.example.administrator.daydayappmarket.recommend.moduls.RecommendApps;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class SearchActivityfirst3Fragment extends Fragment {

    private PullToRefreshListView listView;

    //listView适配器
    private RecommendMainFootListViewAdapter adapter;

    //数据源
    private List<RecommendApps> appses;

//    private MyReceiver receiver;

    private String name;
    private RequestQueue requestQueue;
    private StringRequest request;
    private int index = 1;



    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        appses = new ArrayList<>();
        requestQueue = Volley.newRequestQueue(getContext());
        adapter = new RecommendMainFootListViewAdapter(appses,getContext());

        //获取要搜索的内容
        Bundle arguments = getArguments();

        name = arguments.getString("name");

        //转码
        try {
            name = URLEncoder.encode(name,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        stringrequest(null);
//        IntentFilter filter z

    }

//    class MyReceiver extends BroadcastReceiver {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            intent.getStringExtra("name");
//            stringrequest(null);
//
//        }
//    }


    /**
     * TODO 网络请求数据方法
     * @param refreshView
     */
    private void stringrequest(final PullToRefreshBase<ListView> refreshView) {

        request = new StringRequest(Contacts.SEARCH_THIRD+name+Contacts.PAGE+index
                , new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {


                try {
                    JSONArray jsonArray = new JSONArray(response);
                    if(index == 1){
                        appses.clear();
                    }

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        JSONObject data = jsonObject.getJSONObject("data");
                        RecommendApps apps = new RecommendApps();
                        apps.JsonParse(data);
                        appses.add(apps);
                    }
                    adapter.notifyDataSetChanged();
                    if (refreshView!=null){
                        refreshView.onRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), "shibai", Toast.LENGTH_SHORT).show();
            }
        });

        request.setTag("searchrequest");
        requestQueue.add(request);
        requestQueue.start();
    }


    /**
     * TODO 创建视图
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View inflate = inflater.inflate(R.layout.fragment_recommend_top_first, container, false);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_listview_empty,null);
        ImageView imageView = (ImageView) view.findViewById(R.id.layout_listView_empty_image);
        Glide.with(getContext()).load(R.drawable.cat_loading_transparent).into(imageView);
        listView = (PullToRefreshListView) inflate.findViewById(R.id.fragment_recommend_top_frist_pullToRefreshListView);

        listView.setAdapter(adapter);
        listView.setEmptyView(view);
        listView.setMode(PullToRefreshBase.Mode.BOTH);

        //上拉下拉
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(final PullToRefreshBase<ListView> refreshView) {
                index = 1;
                stringrequest(refreshView);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                index++;
                stringrequest(refreshView);
            }
        });
        return inflate;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        requestQueue.cancelAll("searchrequest");
    }

}
